package tools

import (
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"unicode"
)

func Get(url string) string {
	res, err := http.Get(url)
	if err != nil {
		return ""
	}
	robots, err := io.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		return ""
	}
	return string(robots)
}

// 获取语言
func GetLang(c *gin.Context) string {
	//语言
	acceptLanguage := c.GetHeader("Accept-Language")
	// 使用strings.Split函数按逗号加空格分割字符串
	// 注意：这里直接使用","可能不足以分割所有情况，因为分隔符实际上是", "
	// 更好的做法是使用strings.FieldsFunc，它可以接受一个自定义的分隔符函数
	parts := strings.FieldsFunc(acceptLanguage, func(r rune) bool {
		return r == ',' || unicode.IsSpace(r)
	})
	var lang = "zh-CN"
	// 截取第一个语言标签
	if len(parts) > 0 {
		firstLang := parts[0]
		lang = firstLang
	}
	return lang
}

// Post("http://xxxx","application/json;charset=utf-8",[]byte("{'aaa':'bbb'}"))
func Post(url string, contentType string, body []byte) (string, error) {
	res, err := http.Post(url, contentType, strings.NewReader(string(body)))
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	content, err := io.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}
func PostHeader(url string, msg []byte, headers map[string]string) (string, error) {
	client := &http.Client{}

	req, err := http.NewRequest("POST", url, strings.NewReader(string(msg)))
	if err != nil {
		return "", err
	}
	for key, header := range headers {
		req.Header.Set(key, header)
	}
	resp, err := client.Do(req)
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}
func IsMobile(userAgent string) bool {
	mobileRe, _ := regexp.Compile("(?i:Mobile|iPod|iPhone|Android|Opera Mini|BlackBerry|webOS|UCWEB|Blazer|PSP)")
	str := mobileRe.FindString(userAgent)
	if str != "" {
		return true
	}
	return false
}

// 发送http post请求数据为form
func PostForm(url string, data url.Values) (string, error) {
	resp, err := http.PostForm(url, data)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	content, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}
